﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace iBing.AutoUpdateSelf
{
    public partial class FrmDownload : Form
    {

        private string localConfigPath = Application.StartupPath + "\\updatepro.xml";
        private string remoteConfigPath = Application.StartupPath + "\\updateserver.xml";
        private string filePath = Application.StartupPath + "\\AutoUpdate.exe";
        private bool isSuccess = false;
        private LocalConfig localConfig = null;
        private RemoteConfig remoteConfig = null;

        public FrmDownload()
        {
            InitializeComponent();
        }

        private void FrmDownload_Load(object sender, EventArgs e)
        {
            if (File.Exists(localConfigPath))
                localConfig = LocalConfig.GetLocalConfig(localConfigPath);
            if (File.Exists(remoteConfigPath))
                remoteConfig = RemoteConfig.GetRemoteConfig(remoteConfigPath);

            string strUri = localConfig.ServerUrl;
            strUri = strUri.Substring(0,strUri.LastIndexOf('/'));
            strUri = strUri +"/"+ Path.GetFileName(filePath);

            WebClient wc = new WebClient();
            wc.DownloadFileAsync(new Uri(strUri), filePath + ".tmp");
            wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
            wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);
        }

        void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (this.isSuccess)
            {
                File.Replace(filePath + ".tmp", filePath, filePath + ".bak", true);
            }

            this.localConfig.AutoUpdateVer = this.remoteConfig.AutoUpdateVer;
            this.localConfig.SaveConfig(localConfigPath);

            System.Diagnostics.Process.Start(filePath, "true");
            Environment.Exit(0);
        }

        void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            if (e.ProgressPercentage == 100)
                isSuccess = true;

            this.proBar.Value = e.ProgressPercentage;
        }

    }
}